// 模拟的文章数据，使用数组存储多篇文章的信息
const articles = [
  {
    id: 1,
    title: '第一条：博客简介',
    content: 'This is a short introduction to the world of blogging. It\'s a great way to share your thoughts and ideas with the world.',
    likes: 0,
    comments: []
  },
  {
    id: 2,
    title: '第二条：提高写作水平技巧',
    content: 'Here are some useful tips to improve your writing skills and make your blog posts more interesting and engaging.',
    likes: 0,
    comments: []
  }
];

// 获取页面中的重要元素
const articleDisplayCountSelect = document.getElementById('article-display-count');
const articlesContainer = document.getElementById('articles-container');
const addArticleForm = document.getElementById('add-article-form');
const sidebarItems = document.querySelectorAll('.sidebar li');
const homeItem = document.querySelector('.sidebar li:first-child');
const aboutMeSection = document.getElementById('about-me-section');
const contactUsSection = document.getElementById('contact-us-section');

// 跳转到登录页面的函数
function goToLoginPage() {
  location.href = 'login.html';
}

// 根据选择的数量显示文章的函数
function changeArticleDisplayCount() {
  const selectedValue = articleDisplayCountSelect.value;
  articlesContainer.innerHTML = '';
  for (let i = 0; i < selectedValue; i++) {
    const article = articles[i];
    const articleDiv = createArticleElement(article);
    articlesContainer.appendChild(articleDiv);
  }
}

// 创建单个文章元素的函数
function createArticleElement(article) {
  const articleDiv = document.createElement('div');
  articleDiv.classList.add('article');
  articleDiv.dataset.articleId = article.id;

  const h2 = document.createElement('h2');
  h2.textContent = article.title;
  h2.addEventListener('click', () => toggleDetails(article.id));

  const p = document.createElement('p');
  p.textContent = article.content.substring(0, 100) + '...';

  const readMoreButton = document.createElement('button');
  readMoreButton.textContent = 'Read More';
  readMoreButton.addEventListener('click', () => toggleDetails(article.id));

  const likeButton = document.createElement('button');
  likeButton.classList.add('like-button');
  likeButton.textContent = 'Like';
  const likeCountSpan = document.createElement('span');
  likeCountSpan.id = `like-count-${article.id}`;
  likeCountSpan.textContent = article.likes;
  likeButton.appendChild(likeCountSpan);
  likeButton.addEventListener('click', () => likeArticle(article.id));

  const articleDetailsDiv = document.createElement('div');
  articleDetailsDiv.id = `article-details-${article.id}`;
  articleDetailsDiv.style.display = 'none';
  const fullContentP = document.createElement('p');
  fullContentP.textContent = article.content;
  articleDetailsDiv.appendChild(fullContentP);

  const commentSection = createCommentSection(article);

  const deleteArticleButton = document.createElement('button');
  deleteArticleButton.classList.add('delete-article-button');
  deleteArticleButton.textContent = '删除文章';
  deleteArticleButton.addEventListener('click', () => deleteArticle(article.id));

  articleDiv.appendChild(h2);
  articleDiv.appendChild(p);
  articleDiv.appendChild(readMoreButton);
  articleDiv.appendChild(likeButton);
  articleDiv.appendChild(articleDetailsDiv);
  articleDiv.appendChild(commentSection);
  articleDiv.appendChild(deleteArticleButton);

  return articleDiv;
}

// 创建文章评论区域的函数（将创建评论区域的逻辑提取出来，方便复用和维护）
function createCommentSection(article) {
  const commentSection = document.createElement('div');
  commentSection.classList.add('comment-section');

  const commentTitle = document.createElement('h3');
  commentTitle.textContent = '评论';
  commentSection.appendChild(commentTitle);

  const commentForm = document.createElement('form');
  commentForm.addEventListener('submit', handleCommentSubmit(article));

  const commentInput = document.createElement('input');
  commentInput.type = 'text';
  commentInput.id = `comment-input-${article.id}`;
  commentInput.placeholder = '发表评论...';
  commentInput.classList.add('comment-input');
  commentForm.appendChild(commentInput);

  const addCommentButton = document.createElement('button');
  addCommentButton.textContent = '提交评论';
  addCommentButton.addEventListener('click', () => commentForm.dispatchEvent(new Event('submit')));
  commentForm.appendChild(addCommentButton);

  commentSection.appendChild(commentForm);

  article.comments.forEach((comment) => {
    const commentDiv = createCommentElement(comment);
    commentSection.appendChild(commentDiv);
  });

  return commentSection;
}

// 创建单个评论元素的函数
function createCommentElement(commentText) {
  const commentDiv = document.createElement('div');
  commentDiv.classList.add('comment');
  const commentP = document.createElement('p');
  commentP.textContent = commentText;
  const deleteCommentButton = document.createElement('button');
  deleteCommentButton.textContent = '删除评论';
  deleteCommentButton.addEventListener('click', () => {
    const article = findArticleByComment(commentText);
    if (article) {
      const index = article.comments.indexOf(commentText);
      if (index > -1) {
        article.comments.splice(index, 1);
      }
      commentDiv.remove();
    }
  });
  commentDiv.appendChild(commentP);
  commentDiv.appendChild(deleteCommentButton);
  return commentDiv;
}

// 处理评论提交的函数（将评论提交的逻辑提取出来，方便复用和维护）
function handleCommentSubmit(article) {
  return function (e) {
    e.preventDefault();
    const commentText = document.getElementById(`comment-input-${article.id}`).value;
    if (commentText) {
      article.comments.push(commentText);
      const commentDiv = createCommentElement(commentText);
      const commentSection = document.querySelector(`#article-${article.id}.comment-section`);
      commentSection.insertBefore(commentDiv, commentSection.querySelector('form'));
      document.getElementById(`comment-input-${article.id}`).value = '';
    }
  };
}

// 根据评论内容查找对应的文章的函数（方便在删除评论等操作时找到所属文章）
function findArticleByComment(commentText) {
  return articles.find((article) => article.comments.includes(commentText));
}

// 切换文章详情显示隐藏的函数
function toggleDetails(articleId) {
  const detailsDiv = document.getElementById(`article-details-${articleId}`);
  detailsDiv.style.display = detailsDiv.style.display === 'none'? 'block' : 'none';
}

// 文章点赞函数
function likeArticle(articleId) {
  const likeCountSpan = document.getElementById(`like-count-${articleId}`);
  likeCountSpan.textContent = parseInt(likeCountSpan.textContent) + 1;
}

// 切换添加文章表单显示隐藏的函数
function toggleAddArticleForm() {
  addArticleForm.style.display = addArticleForm.style.display === 'none'? 'block' : 'none';
}

// 标记首页为激活状态并滚动到页面顶部的函数
function showHomePage() {
  sidebarItems.forEach((item) => item.classList.remove('active'));
  homeItem.classList.add('active');
  window.scrollTo({
    top: 0,
    behavior: 'smooth'
  });
}

// 滚动到“关于我”部分的函数
function scrollToAboutMe() {
  if (aboutMeSection) {
    aboutMeSection.scrollIntoView({
      behavior: 'smooth'
    });
  }
}

// 滚动到“联系我们”部分的函数
function scrollToContactUs() {
  if (contactUsSection) {
    contactUsSection.scrollIntoView({
      behavior: 'smooth'
    });
  }
}

// 页面加载完成时初始化文章列表的函数
window.onload = () => {
  for (const article of articles) {
    const articleDiv = createArticleElement(article);
    articlesContainer.appendChild(articleDiv);
  }
};

// 处理文章添加表单提交的函数
addArticleForm.addEventListener('submit', (e) => {
  e.preventDefault();
  const title = document.getElementById('article-title').value;
  const content = document.getElementById('article-content').value;
  const newArticle = {
    id: Date.now(),
    title: title,
    content: content,
    likes: 0,
    comments: []
  };
  articles.push(newArticle);
  const articleDiv = createArticleElement(newArticle);
  articlesContainer.appendChild(articleDiv);
  addArticleForm.reset();
  addArticleForm.style.display = 'none';
});

// 删除文章的函数
function deleteArticle(articleId) {
  const index = articles.findIndex((article) => article.id === articleId);
  if (index > -1) {
    articles.splice(index, 1);
    const articleDiv = document.querySelector(`[data-article-id="${articleId}"]`);
    if (articleDiv) {
      articleDiv.remove();
    }
  }
}